from celery import shared_task
from services.datamodel.vip.models import (UserCardLogs, mm_UserCardBatch)
from services.datamodel.student.models import (mm_Student, mm_StudentTeam)
from services.datamodel.role.models import mm_Role
from django.db import transaction
from apps.student.share import app_logger
from django.utils import timezone
import json
from datetime import datetime, timedelta
from django.db.models import F
from django.core.exceptions import ObjectDoesNotExist
from services.datamodel.activity.models import (mm_GiveTimeActivity)


#@shared_task(ignore_result=True)
def activation_vip(obj=None, user_id=None):
    # 显式的开启一个事务
    with transaction.atomic():
        # 创建事务保存点
        save_id = transaction.savepoint()
        # 暴力回滚
        try:
            UserCardLogs.objects.create(
                seller_student_id=obj.student_id,
                cards=json.dumps([obj.id]),
                buyer_student_id=user_id,
                nums=1,
                day=timezone.now().strftime("%Y-%m-%d"),
                channel=9,  # 原先这里是8， 现在改成9，这里的9也代表激活，只是导出的卡的激活
                expired_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
                role_id=obj.role_id,
            )
            obj.use_student = int(user_id)
            obj.status = 9  # 这里更新成9代表导出的卡激活
            obj.use_time = datetime.now()
            obj.save()
            role = mm_Role.get(id=obj.role_id)
            studentObj = mm_Student.get(id=user_id)
            # origin_exp = studentObj.role_expired_at if studentObj.role_expired_at else datetime.now()
            if studentObj.role_expired_at:
                if studentObj.role_expired_at < datetime.now():
                    origin_exp = datetime.now()
                else:
                    origin_exp = studentObj.role_expired_at
            else:
                origin_exp = datetime.now()
            # 赠送活动
            giveObj = mm_GiveTimeActivity.get_or_default(is_show=1, types=1)
            if giveObj:
                if giveObj.activity_strtime <= datetime.now() and giveObj.activity_endtime >= datetime.now():
                    origin_exp += timedelta(days=giveObj.day)
            studentObj.role_id = obj.role_id
            studentObj.role_expired_at = origin_exp + timedelta(days=role.expire_days)
            studentObj.save()
            cardBatchObj = mm_UserCardBatch.get(id=obj.card_batch_id)
            cardBatchObj.use_num = F('use_num')+1
            cardBatchObj.save()
        except Exception as e:
            app_logger.error(e)
            transaction.savepoint_rollback(save_id)  # 回滚
            # 提交成功，显式的提交一次事务
        transaction.savepoint_commit(save_id)
    return {'retcode': 0, "msg": "OK"}